//app.js
App({
    onLaunch: function () {
        wx.login({
            success: res => {
                console.log(res);
                this.ajax({
                    url: '/api/index/login',
                    data: {
                        code: res.code
                    },
                    success: res => {
                        console.log(res);
                        if (res.code == 1) {
                            var user = wx.getStorageSync('user');
                            wx.setStorageSync('token', res.data.token);
                            wx.setStorageSync('deposit', res.data.deposit);
                            wx.setStorageSync('money', res.data.money);
                            if(!user || user.id != res.data.id) wx.setStorageSync('user', res.data);
                        }
                    }
                });
            }
        });
    },
    globalData: {
        userInfo: null
    },

    //  api_url: 'https://kongjian.yuanchong.net',
    api_url: 'https://bjx.yuanchong.net',

    ajax: function (o, show) {
        if (show) {
            wx.showLoading({
                mask: true,
                title: '正在加载...'
            });
        }
        var data = o.data || {};
        data.token = wx.getStorageSync('token') || '';
        wx.request({
            url: this.api_url + o.url,
            data: data,
            method: o.method || 'POST',
            header: o.header || {
                'content-type': 'application/json'
            },
            success: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                if (res && res.data && res.data.code !== undefined) {
                    if (res.data.code == -1) {
                        wx.showToast({
                            title: '未登录或登陆已失效',
                            icon: 'none'
                        });
                        return false;
                    }
                    if (o.success) o.success(res.data);
                } else {
                    wx.showToast({
                        title: '请求错误',
                        icon: 'none'
                    });
                }
            },
            fail: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                wx.showToast({
                    title: '请求错误',
                    icon: 'none'
                });
            }
        })
    }
})